﻿using System;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace N2.ComponentModel.Design
{
	public class AssemblyNameEditor: FileNameEditor
	{
		protected override void InitializeDialog(OpenFileDialog openFileDialog)
		{
			openFileDialog.DefaultExt = ".dll";
			openFileDialog.Filter = "Assembly files (*.dll)|*.dll";
			openFileDialog.Title = "Select an assembly to load";
		}

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			var _assemblyName = value as AssemblyName;
			
			var _fileName = null == _assemblyName
				? string.Empty
				: Path.GetFullPath(new Uri(_assemblyName.CodeBase).AbsolutePath);//supress "file://"
			
			var _newFileName = (string)base.EditValue(
					context,
					provider,
					_fileName);

			if (!string.IsNullOrEmpty(_newFileName) && (
				null == _assemblyName
					|| !string.Equals(
						_fileName,
						_newFileName,
						StringComparison.OrdinalIgnoreCase))) {
				return AssemblyName.GetAssemblyName(_newFileName);
			}

			return value;
		}
	}
}
